package top.lyunz.fangkeji.webSocketSerevice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import top.lyunz.fangkeji.bean.Equipment;
import top.lyunz.fangkeji.service.equipmentService;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/webSocket/{sid}")
public class WebSocketServer {
	private static ApplicationContext applicationContext;

	public static void setApplicationContext(ApplicationContext context) {
		applicationContext = context;
	}

	static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
	/**
	 * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
	 */
	private static int onlineCount = 0;
	// concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
	private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

	/**
	 * 与某个客户端的连接会话，需要通过它来给客户端发送数据
	 */
	private Session session;

	// 接收sid
	private String sid = "";

	/**
	 * 连接建立成功调用的方法
	 * 
	 * @throws EncodeException
	 */
	@OnOpen
	public void onOpen(Session session, @PathParam("sid") String sid) throws EncodeException {
		this.session = session;
		// 加入set中
		webSocketSet.add(this);
		// 在线数加1
		addOnlineCount();
		logger.info("有新窗口开始监听:识别码为" + sid + ",当前在线人数为" + getOnlineCount());
		this.sid = sid;
		try {
			sendMessage("连接成功");
		} catch (IOException e) {
			//logger.error("websocket IO异常");
		}
	}

	/**
	 * 连接关闭调用的方法
	 */

	@OnClose
	public void onClose() {
		webSocketSet.remove(this); // 从set中删除
		subOnlineCount(); // 在线数减1
		Equipment equipment = new Equipment();
		equipment.setsN(sid);
		equipment.seteStatus(0);
		equipmentService equipmentService = (equipmentService) applicationContext.getBean(equipmentService.class);
		equipmentService.updEquipmentByesN(equipment);

		//logger.info("有一 连接关闭！当前在线人数为" + getOnlineCount());
	}

	/**
	 * 收到客户端消息后调用的方法
	 *
	 * @param message 客户端发送过来的消息
	 * @throws EncodeException
	 */
	@OnMessage
	public void onMessage(String message, Session session) throws EncodeException {
		//logger.info("收到来自窗口" + sid + "的信息:" + message);
		// 群发消息
		for (WebSocketServer item : webSocketSet) {
			try {
				if (sid == sid || sid.equals(sid)) {
					item.sendMessage(message);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 *
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		//logger.error("发生错误");
		error.printStackTrace();
		
		onClose(); 
	}

	/**
	 * 实现服务器主动推送
	 * 
	 * @throws EncodeException
	 */
	public void sendMessage(String message) throws IOException, EncodeException {
		this.session.getBasicRemote().sendText(message);

	}

	/**
	 * 群发自定义消息
	 * 
	 * @throws EncodeException
	 */
	public static boolean sendInfo(String message, @PathParam("sid") String sid) throws IOException, EncodeException {
		//logger.info("推送消息到窗口" + sid + "，推送内容:" + message);
		boolean is = false;
		for (WebSocketServer item : webSocketSet) {
			try {
				if (sid == sid || sid.equals(sid)) {
					item.sendMessage(message);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return is;
	}

	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	public static synchronized void addOnlineCount() {
		WebSocketServer.onlineCount++;
	}

	public static synchronized void subOnlineCount() {
		WebSocketServer.onlineCount--;
	}
}